<?php

namespace App\Models\Kms\Task;

use App\Models\BaseModel;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class TaskTemplateModel extends BaseModel
{
    use HasFactory;

    protected $table = "kms_task_template";

    protected $fillable = [
        "templateType",
        "templateName",
        "status",
        "source",
        "createdAt",
        "createdByUid"
    ];

    const SOURCE_SYSTEM = 0;
    const SOURCE_USER   = 1;

    const STATUS_ON  = 1;
    const STATUS_OFF = 0;

    const TEMPLATE_TYPE_0    = 0;
    const TEMPLATE_TYPE_1    = 1;
    const TEMPLATE_TYPE_TEXT = [
        self::TEMPLATE_TYPE_0 => "kms - 每日任务",
        self::TEMPLATE_TYPE_1 => "客服 - 每日任务",
    ];


    /**
     * @param int $uid
     * @param int $templateType
     * @param int $source
     * @param int $status
     * @return Builder|Model
     */
    public static function generateTemplate(
        int $uid,
        int $templateType,
        int $source = self::SOURCE_SYSTEM,
        int $status = self::STATUS_ON
    ) {
        return self::query()->create([
            "templateType" => $templateType,
            "templateName" => self::TEMPLATE_TYPE_TEXT[$templateType] ?? "",
            "source"       => $source,
            "status"       => $status,
            "createdAt"    => time(),
            "createdByUid" => $uid
        ]);
    }

    /**
     * @return HasMany
     */
    public function templateNodesRel(): HasMany
    {
        return $this->hasMany(TaskTemplateNodesModel::class, "templateId", "id")->orderBy("step");
    }
}
